package com.cjzuji.rental.controller.excel;

import com.alibaba.excel.EasyExcel;
import com.cjzuji.rental.Bean.ApiResponse;
import com.cjzuji.rental.Bean.ExcelData;
import com.cjzuji.rental.service.RedisService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/excel")
public class DataProcessing {
    private static final Logger log = LoggerFactory.getLogger(DataProcessing.class);
    // 定义一个正则表达式来匹配中国大陆的手机号
    private static final String PHONE_NUMBER_REGEX = "^1[3-9]\\d{9}$";
    @Autowired
    private RedisService redisService;

    @PostMapping("/uploadText")
    public void uploadTestExcel(@RequestParam("file") MultipartFile file) {
        try {
            //获取文件流
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            // 提取后缀名
            String originalFilename = file.getOriginalFilename();
            // 提取后缀名
            int lastDotIndex = originalFilename.lastIndexOf('.');
            String name = originalFilename.substring(lastDotIndex + 1);
            //床架一个工作表
            // 根据文件扩展名或内容判断是 .xls 还是 .xlsx
            Workbook workbook = null;
            if (name.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(fileInputStream); // 处理 .xlsx 文件
            } else if (name.endsWith("xls")) {
                workbook = new HSSFWorkbook(fileInputStream); // 处理 .xls 文件
            } else {
                throw new IllegalArgumentException("The specified file is not Excel format");
            }

            //获取 sheet 第0个
            Sheet sheet = workbook.getSheetAt(0);
            List<Map<String, String>> data = new ArrayList<>();
            for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                //获取行
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                Map<String, String> basicInfo = new LinkedHashMap<>();
                for (int j = 0; j < row.getLastCellNum() + 1; j++) {
                    if (row.getCell(j) == null) {
                        continue;
                    }
                    //获取列
                    Cell cell = row.getCell(j);
                    String content = cell.getStringCellValue();
                    String[] lines = content.split("\n");

                    List<String> lines2 = new ArrayList<>();
                    for (String line : lines) {
                        String trimmedLine = line.trim(); // 去除首尾空白字符
                        log.info("打印数据 =====");
                        log.info(trimmedLine);
                        if (!trimmedLine.isEmpty()) { // 忽略空行
                            lines2.add(trimmedLine);
                        }
                    }
                    // 遍历数组，步长为 2
                    for (int k = 0; k < lines2.size(); k += 2) {
//                        System.out.println(isValidPhoneNumber(lines2.get(k+1)));
                        // 确保数组中至少还有两个元素可以组成键值对
//                        if (k + 1 < lines2.size()) {
//
//                            if (isValidPhoneNumber(lines2.get(k+1))) {
//                                basicInfo.put("mobile", lines2.get(k +1 ));
//                                basicInfo.put("name", lines2.get(k));
//                            }
//                            basicInfo.put(lines2.get(k), lines2.get(k + 1));
//                        }
                        log.info("打印key======");
                        log.info(lines2.get(k+1));
                    }
                }
//                if (basicInfo.size() > 0) {
//                    data.add(basicInfo);
//                }
            }
            fileInputStream.close();


        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    @PostMapping("/upload")
    public List<Map<String, String>> uploadComplexExcel(@RequestParam("file") MultipartFile file) {
        try {
            //获取文件流
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            // 提取后缀名
            String originalFilename = file.getOriginalFilename();
            // 提取后缀名
            int lastDotIndex = originalFilename.lastIndexOf('.');
            String name = originalFilename.substring(lastDotIndex + 1);
            //床架一个工作表
            // 根据文件扩展名或内容判断是 .xls 还是 .xlsx
            Workbook workbook = null;
            if (name.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(fileInputStream); // 处理 .xlsx 文件
            } else if (name.endsWith("xls")) {
                workbook = new HSSFWorkbook(fileInputStream); // 处理 .xls 文件
            } else {
                throw new IllegalArgumentException("The specified file is not Excel format");
            }
            //获取 sheet 第0个
            Sheet sheet = workbook.getSheetAt(0);
            List<Map<String, String>> data = new ArrayList<>();
            for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                //获取行
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                Map<String, String> basicInfo = new LinkedHashMap<>();
                for (int j = 0; j < row.getLastCellNum() + 1; j++) {
                    if (row.getCell(j) == null) {
                        continue;
                    }
                    //获取列
                    Cell cell = row.getCell(j);
                    String content = cell.getStringCellValue();
                    String[] lines = content.split("\n");

                    List<String> lines2 = new ArrayList<>();
                    for (String line : lines) {
                        String trimmedLine = line.trim(); // 去除首尾空白字符
                        if (!trimmedLine.isEmpty()) { // 忽略空行
                            if (!trimmedLine.equals("首租订单")){
                                lines2.add(trimmedLine);
                            }
                        }
                    }
                    // 遍历数组，步长为 2
                    for (int k = 0; k < lines2.size(); k += 2) {

//                        System.out.println(isValidPhoneNumber(lines2.get(k+1)));
                        // 确保数组中至少还有两个元素可以组成键值对
                        if (k + 1 < lines2.size()) {

                            if (isValidPhoneNumber(lines2.get(k+1))) {
                                basicInfo.put("mobile", lines2.get(k +1 ));
                                basicInfo.put("name", lines2.get(k));
                            }
                            basicInfo.put(lines2.get(k), lines2.get(k + 1));
                        }
                    }
                }
                if (basicInfo.size() > 0) {
                    data.add(basicInfo);
                }
            }
            fileInputStream.close();
            //将data转json字符串 然后保存到redis中
            // 使用 Jackson 将 List<Map<String, String>> 转换为 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String jsonString = objectMapper.writeValueAsString(data);
                redisService.set("youpinzu", jsonString);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return data;
        }catch (Exception e){
            return null;
        }
    }


    @PostMapping("/getExcel")
    public ApiResponse<List<Map<String, String>>>  getExcelList(@RequestBody ExcelData data){
        int startTime = data.getStartTime();
        int endTime = data.getEndTime();
        //获取Redis中的缓存数据
        Object jsonString = redisService.get("youpinzu");
        // 使用 Jackson 将 JSON 字符串转换为 List<Map<String, String>>
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, String>> list = new ArrayList<>();
        try {
          list = objectMapper.readValue(jsonString.toString(), new TypeReference<List<Map<String, String>>>() {});
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, String>> newList = new ArrayList<>();
        if (startTime != 0 && endTime != 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, String> map = list.get(i);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date date = sdf.parse(map.get("下单时间"));
                    long payTime = date.getTime() /1000;
                    if (payTime >= startTime && payTime <= endTime) {
                        newList.add(map);
                    }
                } catch (Exception e) {
                    System.out.println("日期格式解析错误: " + e.getMessage());
                }
            }
            return ApiResponse.success(newList);
        }
        return ApiResponse.success(list);
    }


    public static boolean isValidPhoneNumber(String phoneNumber) {
        if (phoneNumber == null) {
            return false;
        }

        Pattern pattern = Pattern.compile(PHONE_NUMBER_REGEX);
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }
}
